import scala.io.StdIn
import java.time.LocalDateTime
import scala.util.{Try, Success, Failure}

case class Member(
                   cardId: String,
                   name: String,
                   var password: String,
                   var points: Int,
                   regTime: LocalDateTime
                 )

object SupermarketSystem {
  private val members = scala.collection.mutable.ListBuffer.empty[Member]

  // 主入口
  def main(args: Array[String]): Unit = {
    while(true) {
      showMenu()
      StdIn.readLine("请选择：") match {
        case "1" => accumulatePoints()
        case "2" => redeemPoints()
        case "3" => checkPoints()
        case "4" => changePassword()
        case "5" => registerCard()
        case "6" => System.exit(0)
        case _   => println("无效选项！")
      }
    }
  }

  // 菜单显示
  private def showMenu(): Unit = {
    println("""
              |***************************************
              |*     欢迎进入超市会员管理系统       *
              |*          1. 积分累计                *
              |*          2. 积分兑换                *
              |*          3. 查询剩余积分            *
              |*          4. 修改密码                *
              |*          5. 开卡                   *
              |*          6. 退出                   *
              |***************************************
      """.stripMargin)
  }

  // 开卡功能
  private def registerCard(): Unit = {
    val name = StdIn.readLine("请输入姓名：")
    val password = validatePassword()
    val cardId = generateCardId()
    members += Member(cardId, name, password, 100, LocalDateTime.now())
    println(s"开卡成功！卡号：$cardId 初始积分：100")
  }

  // 生成唯一卡号
  private def generateCardId(): String = {
    val timestamp = System.currentTimeMillis().toString
    s"VIP${timestamp.takeRight(6)}"
  }

  // 密码验证
  private def validatePassword(): String = {
    var password = ""
    do {
      password = StdIn.readLine("设置密码（至少6位）：")
    } while(password.length < 6)
    password
  }

  // 积分累计
  private def accumulatePoints(): Unit = {
    authenticateMember() match {
      case Some(member) =>
        println("请输入消费金额：")
        Try(StdIn.readDouble()) match {
          case Success(amount) if amount > 0 =>
            member.points += amount.toInt
            println(s"成功累计${amount.toInt}积分，当前总积分：${member.points}")
          case _ => println("无效的金额输入")
        }
      case None => println("认证失败")
    }
  }

  // 积分兑换
  private def redeemPoints(): Unit = {
    authenticateMember() match {
      case Some(member) =>
        println("请选择兑换礼品：")
        println("1: 炒锅（1000积分）")
        println("2: 洗手液（800积分）")
        println("3: 餐巾纸（400积分）")

        StdIn.readLine() match {
          case "1" => deductPoints(member, 1000, "炒锅")
          case "2" => deductPoints(member, 800, "洗手液")
          case "3" => deductPoints(member, 400, "餐巾纸")
          case _ => println("无效选项")
        }
      case None => println("认证失败")
    }
  }

  // 查询积分
  private def checkPoints(): Unit = {
    authenticateMember() match {
      case Some(member) =>
        println(s"""
                   |会员信息：
                   |卡号：${member.cardId}
                   |姓名：${member.name}
                   |剩余积分：${member.points}
                   |注册时间：${member.regTime}
                   |""".stripMargin)
      case None => println("认证失败")
    }
  }

  // 修改密码
  private def changePassword(): Unit = {
    authenticateMember() match {
      case Some(member) =>
        val newPassword = validatePassword()
        member.password = newPassword
        println("密码修改成功！")
      case None => println("认证失败")
    }
  }

  // 认证辅助方法
  private def authenticateMember(): Option[Member] = {
    val cardId = StdIn.readLine("请输入卡号：")
    val password = StdIn.readLine("请输入密码：")
    members.find(m => m.cardId == cardId && m.password == password)
  }

  // 积分扣除逻辑
  private def deductPoints(member: Member, points: Int, item: String): Unit = {
    if(member.points >= points) {
      member.points -= points
      println(s"成功兑换$item，剩余积分：${member.points}")
    } else {
      println("积分不足！")
    }
  }
}